Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
How to create 2d array using "for" loop in Javascript?

I need to write a program that creates a 2d array in variable "numbers" in rows (5) and columns (4). The elements of the array have to be consecutive integers starting at 1 and end at 20. I have to use "for" loop.

[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ],
[ 17, 18, 19, 20 ],

So I came up with that:

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i++) {
    numbers [i] = [];
    for (let j = 0; j < columns; j++){
        numbers  [i][j] = j + 1;
    }
}
console.log(numbers); 

But the result of this is five identical rows, like this:

      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ]

Do you have any idea how to fix it? How to make second row starting from 5?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Looks like in the second loop, you should do numbers [i][j] = j * i; instead

about 4 years ago · Juan Pablo Isaza Report

0

Every time the outer for loop starts a new iteration, j is reset back to 0, which is why you keep getting rows starting with 1.

To fix this, you could declare a variable outside of the for loops that tracks the current number, and use that instead of j like so:

const numbers = [];
const columns = 4;
const rows = 5;
let currNum = 0;

for (let i = 0; i < rows; i++) {
    numbers [i] = [];
    for (let j = 0; j < columns; j++){
        currNum++;
        numbers  [i][j] = currNum;
    }
}
console.log(numbers); 
about 4 years ago · Juan Pablo Isaza Report

0

Here is some updated code. You need to add i*columns to every value

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i++) {
    numbers[i] = [];
    for (let j = 0; j < columns; j++){
        numbers[i][j] = j + 1 + (i*columns);
    }
}
console.log(numbers); 

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!